//
//  AppDelegate.m
//  闪电修
//
//  Created by aojun on 17/10/16.
//  Copyright © 2017年 aojun. All rights reserved.
//

#import "AppDelegate.h"
#import "SDLoginVC.h"
#import "UINavigationController+GGInteractiveTransition.h"
#import "AppDelegate+Pay.h"
#import <AMapFoundationKit/AMapFoundationKit.h>


// 引入JPush功能所需头文件
#import "JPUSHService.h"
// iOS10注册APNs所需头文件
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
#import <UserNotifications/UserNotifications.h>
#endif
// 如果需要使用idfa功能所需要引入的头文件（可选）
#import <AdSupport/AdSupport.h>


#import "MCFileManage.h"
//$(PRODUCT_BUNDLE_IDENTIFIER)

extern NSString * fileName;
extern NSString * ziFileName;

@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

@implementation AppDelegate
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
 
    
    BOOL is = [MCFileManage deletableFileName:fileName pathType:pathTmpType];
    NSLog(@"删除离线保存 %d",is);
    BOOL is1 = [MCFileManage deletableFileName:ziFileName pathType:pathTmpType];
    NSLog(@"删除离线保存 %d",is1);
    
    
    // 高德地图
    [AMapServices sharedServices].apiKey = KGaoDe_key;
    //开启地图地位服务
    [AMapServices sharedServices].enableHTTPS= YES;

    //向微信注册
    [WXApi registerApp:@"wxf72020797fb885e7" withDescription:@"demo 2.0"];
    
    NSString *token = [UserInfoManager currentToken];
    UIViewController *vc1;
    if (kStringIsEmpty(token)==YES) {
        SDLoginVC *vc =[SDLoginVC new];
        vc.type =appearTypePush;
        vc1 = (id)vc;
    }else
    {
        WSELF(weakSelf);
        SDPublishWeiXiuVC *nvc = [[SDPublishWeiXiuVC alloc]init];
        nvc.click = ^(NSInteger tag)
        {
            [UIView transitionWithView:[UIApplication sharedApplication].keyWindow duration:0.3f options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
                BOOL oldState = [UIView areAnimationsEnabled];
                [UIView setAnimationsEnabled:NO];
                weakSelf.window.rootViewController = weakSelf.tabBarController;
                weakSelf.tabBarController.selectedIndex =tag;
                [UIView setAnimationsEnabled:oldState];
            } completion:^(BOOL finished) {

            }];
        };
        vc1 = (id)nvc;

    }
    
    //导航栏
    UINavigationBar *nb = [UINavigationBar appearance];
    nb.titleTextAttributes = @{
                               NSForegroundColorAttributeName:[UIColor whiteColor],
                               NSFontAttributeName: [UIFont systemFontOfSize:kFitW(16)],
                               };
    nb.barTintColor = hexCOLOR(@"#cc2c2c");
    nb.tintColor = [UIColor whiteColor];

    UINavigationController *nac = [[UINavigationController alloc]initWithRootViewController:vc1];

    self.window.rootViewController = nac;
    
    [self.window makeKeyAndVisible];
 
    
    [application setApplicationIconBadgeNumber:0];
    //极光推送
    [self _setJiGuanConfiForOptions:launchOptions application:application];
    
    return YES;
    
}


-(void)_setJiGuanConfiForOptions:(NSDictionary *)launchOptions application:(UIApplication *)application
{
    
    // 注册apns通知
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) // iOS10
    {
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;;
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];

    }
    
    else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) // iOS8, iOS9
    {
        // categories 可以设置不同类别的推送，在收到推送的代理方法中根据categories的identifier进行不同的推送处理
        UIUserNotificationType notificationTypes = UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound;
        UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:notificationTypes categories:nil];
        
        [application registerUserNotificationSettings:setting];
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:notificationTypes categories:nil];
    }
    else // iOS7
    {
        //categories 必须为nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert) categories:nil];
    }
    
    
    
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        NSLog(@"%@",registrationID);
    }];
    
     /*
     *  launchingOption 启动参数.
     *  appKey 一个JPush 应用必须的,唯一的标识.
     *  channel 发布渠道. 可选.
     *  isProduction 是否生产环境. 如果为开发状态,设置为 NO; 如果为生产状态,应改为 YES.
     *  advertisingIdentifier 广告标识符（IDFA） 如果不需要使用IDFA，传nil.
     * 此接口必须在 App 启动时调用, 否则 JPush SDK 将无法正常工作.
     */
    // 广告标识符
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    // 如不需要使用IDFA，advertisingIdentifier 可为nil
    // 注册极光推送
//    [JPUSHService setupWithOption:launchOptions appKey:JPUSHAPPKEY channel:channel apsForProduction:isProduction advertisingIdentifier:advertisingId];
    
    [JPUSHService setupWithOption:launchOptions appKey:KJGKey
                          channel:@"App Store"
                 apsForProduction:isProduction
            advertisingIdentifier:advertisingId];
    
   
  
    
    NSString *UserId = [[UserInfoManager currentId] stringValue];
    
    
    if (UserId) {
        
        
        // 推送标签
        [JPUSHService setTags:[NSSet setWithObject:@"user"]  completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
            NSLog(@"极光 ---%ld",iResCode);
        } seq:0];
        // 推送别名
        [JPUSHService setAlias:UserId completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
            NSLog(@"极光 ---%ld",iResCode);
        } seq:0];
        
//        //登录
//        [JPUSHService setTags:nil alias:userNmae callbackSelector:@selector(tagsAliasCallback:tags:alias:) object:self];
//        - (void)tagsAliasCallback:(int)iResCode tags:(NSSet*)tags alias:(NSString*)alias {
//            NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, tags , alias);
//        }
//        //退出登录
//        [JPUSHService setTags:nil alias:@"" callbackSelector:@selector(tagsAliasCallback:tags:alias:) object:self];
//        - (void)tagsAliasCallback:(int)iResCode tags:(NSSet*)tags alias:(NSString*)alias {
//            NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, tags , alias);
//        }
        
    }

    
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];

//    if (launchOptions) {
//
//        NSDictionary * remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
//
//        if (remoteNotification) {
//            NSLog(@"推送消息==== 这个判断是在程序没有运行的情况下收到通知，点击通知跳转页面%@",remoteNotification);
//        }
//    }
    
}


#pragma mark 获取自定义消息推送内容
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    
    NSDictionary * userInfo = [notification userInfo];
    
    NSString *info = userInfo[@"title"];
    if ([info isEqualToString:@"info"]) {
    
        [[NSNotificationCenter defaultCenter]postNotificationName:GongGaoNotification object:nil userInfo:userInfo];
        
    }else
    {
        //扫描后可以跳转了
        [[NSNotificationCenter defaultCenter]postNotificationName:saoMiaoNotification object:nil userInfo:nil];
        
    }
    
    NSLog(@"%@---userInfo-获取自定义消息推送内容",userInfo);
    
    
    //[JPUSHService handleRemoteNotification:userInfo];
    
    //[[TCPushManager sharedPushManager] networkReceiveMessage:userInfo];
}







- (void)applicationDidEnterBackground:(UIApplication *)application {
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
}

// ---------------------------------------------------------------------------------
#pragma mark - 注册推送回调获取 DeviceToken
#pragma mark -- 成功
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    // 注册成功
    // 极光: Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}

#pragma mark -- 失败
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    // 注册失败
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    [JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
}


// 收到远程推送时，程序在前台，或者程序在后台但是点击了收到的推送通知打开程序 //NS_AVAILABLE_IOS(7_0);
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    if ([[UIDevice currentDevice].systemVersion floatValue] < 10.0) {
        NSString * alert = userInfo[@"aps"][@"alert"];
        if (8.0<[[UIDevice currentDevice].systemVersion floatValue] < 10.0) {
            
            UILocalNotification *noti = [[UILocalNotification alloc] init];
            
            if (noti) {
                
                //设置推送时间
                
                noti.fireDate = [NSDate dateWithTimeIntervalSinceNow:10];//=now
                
                //设置时区
                
                noti.timeZone = [NSTimeZone defaultTimeZone];
                
                //设置重复间隔
                
                noti.repeatInterval = 1;
                
                //推送声音
                
                noti.soundName = UILocalNotificationDefaultSoundName;
                
                //内容
                
                noti.alertBody = alert;
                
                //显示在icon上的红色圈中的数子
                
                noti.applicationIconBadgeNumber = 1;
                
                //设置userinfo 方便在之后需要撤销的时候使用
                
                NSDictionary *infoDic = @{};
                
                noti.userInfo = infoDic;
                
                //添加推送到uiapplication
                
                UIApplication *app = [UIApplication sharedApplication];
                
                [app scheduleLocalNotification:noti];
        }
    
        
        }
    // iOS7之后调用这个
    [JPUSHService handleRemoteNotification:userInfo];
    
    
    
    if ([alert isEqualToString:@"维修订单已报价"]) {
        //扫描后可以跳转了
        [[NSNotificationCenter defaultCenter]postNotificationName:yiBaoJiaNotification object:nil userInfo:nil];
        
    }else if ([alert isEqualToString:@"师傅提出价格变动"]) {
        //扫描后可以跳转了
        [[NSNotificationCenter defaultCenter]postNotificationName:bianJiaNotification object:nil userInfo:nil];
    }
    else if ([alert isEqualToString:@"师傅提出支付申请"]) {
        //扫描后可以跳转了
        [[NSNotificationCenter defaultCenter]postNotificationName:jieSuanNotification object:nil userInfo:nil];
    }
    [[UIApplication sharedApplication]setApplicationIconBadgeNumber:0];
        
    
    //completionHandler(UIBackgroundFetchResultNewData);
    
    }else
    {
        //completionHandler(UIBackgroundFetchResultNoData);
    }
    
}



//NS_AVAILABLE_IOS(8_0, 10_0);
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification completionHandler:(void (^)())completionHandler
{
    completionHandler();
}

//NS_AVAILABLE_IOS(9_0, 10_0);
- (void)application:(UIApplication *)application handleActionWithIdentifier:(nullable NSString *)identifier forLocalNotification:(UILocalNotification *)notification withResponseInfo:(NSDictionary *)responseInfo completionHandler:(void(^)())completionHandler {
    completionHandler();
}

- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler
{
    completionHandler();
}
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    
}
#pragma mark - iOS10: 收到推送消息调用(iOS10是通过Delegate实现的回调)
#pragma mark- JPUSHRegisterDelegate
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0

// 当程序在前台时, 收到推送弹出的通知
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    
    
    NSDictionary * userInfo = notification.request.content.userInfo;
     NSString * alert = userInfo[@"aps"][@"alert"];
    if ([alert isEqualToString:@"维修订单已报价"]) {
        
        [[NSNotificationCenter defaultCenter]postNotificationName:yiBaoJiaNotification object:nil userInfo:nil];
        
    }else if ([alert isEqualToString:@"师傅提出价格变动"]) {
        //扫描后可以跳转了
        [[NSNotificationCenter defaultCenter]postNotificationName:bianJiaNotification object:nil userInfo:nil];
    }
    else if ([alert isEqualToString:@"师傅提出支付申请"]) {
        //扫描后可以跳转了
        [[NSNotificationCenter defaultCenter]postNotificationName:jieSuanNotification object:nil userInfo:nil];
    }
    
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]])
    {
        [JPUSHService handleRemoteNotification:userInfo];
       
        //NSString *message = [NSString stringWithFormat:@"will%@", [userInfo[@"aps"] objectForKey:@"alert"]];

    }
    
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
}


// 程序关闭后, 通过点击推送弹出的通知
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]])
    {
        [JPUSHService handleRemoteNotification:userInfo];
//        NSString *message = [NSString stringWithFormat:@"did%@", [userInfo[@"aps"] objectForKey:@"alert"]];
//        NSLog(@"iOS10程序关闭后通过点击推送进入程序弹出的通知: %@", message);
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil,nil];
//        [alert show];
    }
    
    completionHandler();  // 系统要求执行这个方法
}

#endif


- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    //支付宝/微信支付回调
    return [self onOpenAliPayForUrl:url application:application Callback:^(NSDictionary *resultDic) {
        NOTIF_POSTInfo(noteAliPayResult,nil,resultDic);
    }];
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    
    //支付宝/微信支付回调
    return [self onOpenAliPayForUrl:url application:application Callback:^(NSDictionary *resultDic) {
        NOTIF_POSTInfo(noteAliPayResult,nil,resultDic);
    }];
}


// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{    //支付宝／微信支付回调
    return [self onOpenAliPayForUrl:url application:application Callback:^(NSDictionary *resultDic) {
        NOTIF_POSTInfo(noteAliPayResult,nil,resultDic);
    }];
    
}


-(void)onLoadTabbar
{
    self.tabBarController = [MSTabBarController new];
}

+(void)onResignKey
{
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
}
@end

